package com.example.demo_news.service.Admin;

import java.util.List;

import com.example.demo_news.Repository.OfficialRepository;
import com.example.demo_news.Repository.PersonRepository;
import com.example.demo_news.Repository.UserPepository;
import com.example.demo_news.entity.MyUser;
import com.example.demo_news.entity.OfficialAccount;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

@Service
public class AdminUserService {
    @Autowired
    private UserPepository userPepository;
    @Autowired
    private PersonRepository personRepository;
    @Autowired
    private OfficialRepository officialRepository;
//返回所有用户
    public boolean findAllUser(Model model) {
        try {
            List<MyUser> users = userPepository.findAll();
            model.addAttribute("users", users);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    //删除用户
    public boolean deleteUser(Integer id,Model model){
        MyUser user=userPepository.findUserById(id);
        userPepository.delete(user);
        return true;
    }

    //修改用户权限
    public boolean modifyRole(Integer id){
        try {
            MyUser user=userPepository.findUserById(id);
            //更改用户权限,同时新建一个新闻号
            if(user.getRole().equals("user")){
                user.setRole("official");
                OfficialAccount officialAccount=new OfficialAccount();
                officialAccount.setUser(user);
                //保存新闻号
                officialRepository.save(officialAccount);
                //更新user
                user.setOfficialAccount(officialAccount);
                userPepository.flush();
            }
            //更改为普通用户
            else if(user.getRole().equals("official")){
                user.setRole("user");
                OfficialAccount officialAccount=new OfficialAccount();
                officialAccount.setUser(user);
                officialRepository.delete(officialAccount);
                //删除oa表中数据
            }
            return true;
        } catch (Exception e) {
            return false;
        }

       
    }
}
